import useDictStore from '@/store/modules/dict'
import { GetDataDictionary, GetDataDictionaryTree } from '@/api/sys/dict/data'
import dictType from './dictType'
/**
 * 获取字典数据
 */

export function useDict(...args) {
  const res = ref({})
  return (() => {
    args.forEach((dictTypekey, index) => {
      const dictTypeValue = dictType[dictTypekey]
      if (!dictTypeValue) {
        // console.error(`字典类型 ${dictTypekey} 未在 dictType.js 中定义`)
        return
      }
      res.value[dictTypekey] = []
      const dicts = useDictStore().getDict(dictTypekey) //piana获取字典
      if (dicts) {
        res.value[dictTypekey] = dicts
      } else {
        const params = {
          systemId: import.meta.env.VITE_APP_SYS_ID,
          parentCode: dictTypeValue,
          enableFlag: 1,
        }
        GetDataDictionary(params).then((resp) => {
          // console.log('字典:' + dictTypekey + '获取成功', resp)
          res.value[dictTypekey] = resp.output
          useDictStore().setDict(dictTypekey, res.value[dictTypekey])
        })
      }
    })
    return toRefs(res.value)
  })()
}

//获取树形字典数据
export function useTreeDict(...args) {
  const res = ref({})
  return (() => {
    args.forEach((dictTypekey, index) => {
      const dictTypeValue = dictType[dictTypekey]
      if (!dictTypeValue) {
        // console.error(`树形字典类型 ${dictTypekey} 未在 dictType.js 中定义`)
        return
      }
      res.value[dictTypekey] = []
      const dicts = useDictStore().getDict(dictTypekey) //piana获取字典
      if (dicts) {
        res.value[dictTypekey] = dicts
      } else {
        const params = {
          systemId: import.meta.env.VITE_APP_SYS_ID,
          dictionaryCode: dictTypeValue,
          enableFlag: 1,
        }
        GetDataDictionaryTree(params).then((resp) => {
          // console.log(
          //   '树形字典:' + dictTypekey + '获取成功',
          //   typeof resp.output
          // )
          res.value[dictTypekey] = resp.output
          useDictStore().setDict(dictTypekey, res.value[dictTypekey])
        })
      }
    })
    return toRefs(res.value)
  })()
}
